import TodoHeader from "../components/todo-header"
import TodoList from "../components/todo-list"
import TodoBottom from "../components/todo-bottom"
import { createSignal, onMount, Show } from "solid-js"
import type { Component } from "solid-js"
import type { TodoItem } from "./index.d"

const App: Component = () => {
  const [todoList, setTodoList] = createSignal<Array<TodoItem>>([])
  const [isAllCheckedStatus, setIsAllCheckedStatus] = createSignal<boolean>(false)

  const updateIsAllCheckedStatus = () => {
    setIsAllCheckedStatus(todoList().every(todo => todo.isCheck))
  }
  onMount(updateIsAllCheckedStatus)
  const addTodo = (todoName: string) => {
    setTodoList([...todoList(), { name: todoName, isCheck: false }])
    updateIsAllCheckedStatus()
  }
  const removeTodo = (index: number) => {
    setTodoList(todoList().filter((todo, i) => i !== index))
    updateIsAllCheckedStatus()
  }
  const removeAllCheckedTodo = () => {
    setTodoList(todoList().filter(todo => !todo.isCheck))
  }
  const allCheckStatusChange = () => {
    setIsAllCheckedStatus(!isAllCheckedStatus())
    setTodoList(
      todoList().map(todo => ({
        name: todo.name,
        isCheck: isAllCheckedStatus(),
      }))
    )
  }
  const todoCheckStatusChange = () => {
    updateIsAllCheckedStatus()
  }
  return (
    <div>
      <TodoHeader addTodoEvent={addTodo}></TodoHeader>
      <TodoList
        todoList={todoList()}
        removeTodoEvent={removeTodo}
        todoCheckStatusChangeEvent={todoCheckStatusChange}
      ></TodoList>
      <Show when={todoList().length}>
        <TodoBottom
          isAllCheckedStatus={isAllCheckedStatus()}
          allCheckStatusChangeEvent={allCheckStatusChange}
          removeAllCheckedTodoEvent={removeAllCheckedTodo}
        ></TodoBottom>
      </Show>
    </div>
  )
}
export default App
